/**
 * Google登錄工具类
 * 用于Development Build环境
 */

import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';
import { Platform } from 'react-native';
import { GOOGLE_CONFIG } from '../config/googleConfig';

export class GoogleAuthManager {
  private static initialized = false;

  /**
   * 初始化Google登錄
   */
  static async initialize() {
    if (this.initialized) return;

    try {
      // 配置 Google Sign-in（暂时注释掉，避免配置错误）
      GoogleSignin.configure({
        webClientId: GOOGLE_CONFIG.WEB_CLIENT_ID,
        iosClientId: GOOGLE_CONFIG.IOS_CLIENT_ID,
        offlineAccess: GOOGLE_CONFIG.OFFLINE_ACCESS,
        scopes: GOOGLE_CONFIG.SCOPES,
        forceCodeForRefreshToken:GOOGLE_CONFIG.FORCE_CODE_FOR_REFRESH_TOKEN,
      });
      this.initialized = true;
      console.log('Google登錄初始化成功');
    } catch (error) {
      console.error('Google登錄初始化失败:', error);
      throw error;
    }
  }

  /**
   * 检查是否已登录
   */
  static async isSignedIn(): Promise<boolean> {
    try {
      return await GoogleSignin.isSignedIn();
    } catch (error) {
      console.error('检查Google登錄状态失败:', error);
      return false;
    }
  }

  /**
   * 执行Google登錄
   */
  static async signIn() {
    try {
      await this.initialize();
      
      // 检查Google Play服务（Android）
      if (Platform.OS === 'android') {
        await GoogleSignin.hasPlayServices();
      }
      
      // 执行登录
      const userInfo = await GoogleSignin.signIn();
      console.log('Google登錄用户信息:', userInfo);

      // 获取tokens
      const tokens = await GoogleSignin.getTokens();
      console.log('Google登錄tokens:', tokens);

      return {
        userInfo,
        idToken: tokens.idToken,
        accessToken: tokens.accessToken,
      };
    } catch (error: any) {
      console.error('Google登錄失败:', error);
      
      // 处理特定错误
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        throw new Error('用户取消登录');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        throw new Error('登录正在进行中');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        throw new Error('此设备不支持Google Play服务');
      }
      
      throw error;
    }
  }

  /**
   * 登出
   */
  static async signOut() {
    try {
      await GoogleSignin.signOut();
      console.log('Google登出成功');
    } catch (error) {
      console.error('Google登出失败:', error);
      throw error;
    }
  }

  /**
   * 撤销访问权限
   */
  static async revokeAccess() {
    try {
      await GoogleSignin.revokeAccess();
      console.log('Google访问权限撤销成功');
    } catch (error) {
      console.error('Google访问权限撤销失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前用户信息
   */
  static async getCurrentUser() {
    try {
      const userInfo = await GoogleSignin.signInSilently();
      return userInfo;
    } catch (error) {
      console.error('获取Google用户信息失败:', error);
      return null;
    }
  }
}
